<template>
  <div class="page-root">
    <BasePanel>
      <BaseSearch :search="searchProps" @searchData="updateTable" @resetData="updateTable" />
      <div class="table-top-wrap">
        <div class="table-title">
          <span>列表</span>
        </div>
        <div class="btn-gruop">
          <a-button type="primary" @click="handleHit" :disabled="selectedRows.length === 0" ghost>机构撞库</a-button>
          <a-button type="primary" @click="handleHit1" :disabled="selectedRows.length === 0" ghost>API撞库</a-button>
          <a-button type="primary" icon="download" ghost @click="handleExport">进件成功导出</a-button>
          <!-- <a-button type="primary" icon="download" ghost @click="handleExport2">产品进件导出</a-button> -->
          <a-button type="primary" icon="download" ghost @click="handleExport3">表单导出</a-button>
        </div>
      </div>
      <div v-if="isbool">
        <BaseTable :loading="loading" :columns="columns" :dataSource="computedDataSource"
          :selectedRows.sync="selectedRows" :pagination="false" :scroll="{ x: 1000 }">
          <template slot="manualInstitutionResult" slot-scope="{ record }">
            {{ record.manualInstitutionResult ? record.manualInstitutionResult.join(',') : '/' }}
          </template>
          <template slot="manualProductResult" slot-scope="{ record }">
            {{ record.manualProductResult ? record.manualProductResult.join(',') : '/' }}
          </template>
          <template slot="matchingResult" slot-scope="{ record }">
            <a-popover title="匹配机构结果" trigger="click">
              <div slot="content">
                <json-viewer :value="JSON.parse(record.matchingResult || '{}')" :expand-depth="5"
                  :show-array-index="false" :preview-mode="true" sort copyable></json-viewer>
              </div>
              <span class="primary">查看</span>
            </a-popover>
          </template>
          <template slot="userName" slot-scope="{ record }">
            {{ record.formInfo?.userName || '/' }}
          </template>
          <template slot="cityName" slot-scope="{ record }">
            {{ record.formInfo?.cityName || '/' }}
          </template>
          <template slot="loanAmount" slot-scope="{ record }">
            {{ record.formInfo?.loanAmount || '/' }}
          </template>
          <template slot="house" slot-scope="{ record }">
            {{ record.formInfo?.house || '/' }}
          </template>
          <template slot="car" slot-scope="{ record }">
            {{ record.formInfo?.car || '/' }}
          </template>
          <template slot="accumulation" slot-scope="{ record }">
            {{ record.formInfo?.accumulation || '/' }}
          </template>
          <template slot="sesameSeed" slot-scope="{ record }">
            {{ record.formInfo?.sesameSeed || '/' }}
          </template>
          <template slot="overdueSituation" slot-scope="{ record }">
            {{ record.formInfo?.overdueSituation || '/' }}
          </template>
          <template slot="socialSecurity" slot-scope="{ record }">
            {{ record.formInfo?.socialSecurity || '/' }}
          </template>
          <template slot="profession" slot-scope="{ record }">
            {{ record.formInfo?.profession || '/' }}
          </template>
          <template slot="info" slot-scope="{ record }">
            <span class="primary" @click="handleAdjust(record)">线索分析</span>
          </template>
          <template slot="operation" slot-scope="{ record }">
            <span class="primary" @click="handlePull(record.id, record.userId)">机构推送</span>
            <a-divider type="vertical" />
            <span class="primary" @click="handlePull1(record.id, record.userId)">API推送</span>
          </template>
        </BaseTable>
      </div>
      <div v-show="computedDataSource.length > 0" class="page-footer">
        <BasePagination :page-key.sync="pageKey" :get-list="tableInit" />
      </div>
    </BasePanel>
    <FormModal :visible="formShow" :id="id" :userid="userid" @success="successForm" @close="closeForm" />
    <FormModal1 :visible="formShow1" :id="id" :userid="userid" @success="successForm1" @close="closeForm1" />
    <AdjustModal :visible="adjustShow" :id="id" :default="defaultObj" @success="successForm" @close="closeAdjust" />
  </div>
</template>

<script>
import { searchProps, columns } from './option.js';
import * as Ajax from '@/api/institution';
import { ajaxDownload } from '@/utils/export.js';
import FormModal from './form';
import FormModal1 from './form1';
import AdjustModal from './adjust';
export default {
  components: {
    FormModal,
    FormModal1,
    AdjustModal,
  },
  data() {
    return {
      searchProps,
      searchForm: {},
      columns,
      loading: true,
      computedDataSource: [],
      selectedRows: [],
      pageKey: {
        pageSize: 10,
        total: 1,
        current: 1,
      },
      id: '',
      userid: '',
      formShow: false,
      formShow1: false,
      adjustShow: false,
      defaultObj: {},
      isbool: true
    };
  },
  created() {
    this.tableInit();
    this.getSelect();
  },
  methods: {
    async handleExport() {
      this.loading = true
      // const { current, pageSize } = this.pageKey;
      const params = { ...this.searchForm };
      if (params.time) {
        params.startTime = params.time[0] + ' 00:00:00';
        params.endTime = params.time[1] + ' 23:59:59';
      } 
      if (params.time2) {
        params.startPushTime = `${params.time2[0]} 00:00:00`;
        params.endPushTime = `${params.time2[1]} 23:59:59`;
      } 
      delete params.time;
      delete params.time2;
      const queryString = new URLSearchParams(params).toString();
      //  ajaxDownload(`/web/order/list/export?${queryString}`, 'get')(params);
      await ajaxDownload(`/web/institution/apply/export?${queryString}`, 'get')(params);
      this.loading = false

    },

    async handleExport3() {
      this.loading = true
      // const { current, pageSize } = this.pageKey;
      const params = { ...this.searchForm };
      if (params.time) {
        params.startTime = params.time[0] + ' 00:00:00';
        params.endTime = params.time[1] + ' 23:59:59';
      } 
      if (params.time2) {
        params.startPushTime = `${params.time2[0]} 00:00:00`;
        params.endPushTime = `${params.time2[1]} 23:59:59`;
      } 
      delete params.time;
      delete params.time2;
      const queryString = new URLSearchParams(params).toString();
      await ajaxDownload(`/web/institution/clue/export?${queryString}`, 'get')(params);
      this.loading = false
    },

    handleHit() {
      const _this = this;
      this.$confirm({
        title: '机构撞库',
        content: '请确认是否执行机构撞库？',
        onOk() {
          _this.loading = true;
          const clueIdList = _this.selectedRows.map((it) => it.id);
          Ajax.hitClueList({ clueIdList })
            .then(({ success }) => {
              if (success) {
                _this.$message.success('撞库成功');
                _this.tableInit();
                _this.selectedRows = []
              }
            })
            .finally(() => {
              _this.loading = false;
              _this.selectedRows = []
            });
        },
        onCancel() { },
      });
    },
    customRowClassName(record) {
      console.log('拿到的', record)
      // return 'row-highlight'
      // console.log('拿到的值123',record)
      // 根据记录或索引返回自定义的类名  
      // 例如，我们可以根据年龄是否大于35来设置不同的类名  
      // return record.age > 35 ? 'row-highlight' : '';  
    },
    handleHit1() {
      const _this = this;
      this.$confirm({
        title: 'API撞库',
        content: '请确认是否执行API撞库？',
        onOk() {
          _this.loading = true;
          const clueIdList = _this.selectedRows.map((it) => it.id);
          Ajax.hitClueList1({ clueIdList })
            .then(({ success }) => {
              if (success) {
                _this.$message.success('撞库成功');
                _this.tableInit();
                _this.selectedRows = []
              }
            })
            .finally(() => {
              _this.loading = false;
            });
        },
        onCancel() { },
      });
    },
    getSelect() {
      Ajax.getChannelSelect().then((res) => {
        if (res.success) {
          searchProps[0].selectOptions = Array.isArray(res.data)
            ? res.data.map((it) => ({
              ...it,
              label: it.channelName,
              value: it.id,
            }))
            : [];
        }
      });
    },
    updateTable(params = {}) {
      this.searchForm = { ...params };
      this.pageKey = this.$options.data().pageKey;
      this.tableInit();
    },
    // table 初始化
    tableInit() {

      this.loading = true;
      const { current, pageSize } = this.pageKey;
      const params = { pageNum: current, pageSize, ...this.searchForm };
      if (params.time) {
        params.startTime = `${params.time[0]} 00:00:00`;
        params.endTime = `${params.time[1]} 23:59:59`;
      } else {
        params.startTime = '';
        params.endTime = '';
      }
      delete params.time1;
      if (params.time2) {
        params.startPushTime = `${params.time2[0]} 00:00:00`;
        params.endPushTime = `${params.time2[1]} 23:59:59`;
      } else {
        params.startPushTime = '';
        params.endPushTime = '';
      }
      delete params.time;
      delete params.time2;
      Ajax.getClueList(params)
        .then((res) => {
          this.isbool = false
          this.isbool = true
          const { data, totalCount } = res;
          this.computedDataSource = Array.isArray(data) ? data : [];
          this.pageKey.total = totalCount;
        })
        .finally(() => {
          this.isbool = false
          this.isbool = true
          this.loading = false;
        });
    },
    handleAdjust(record) {
      const { id, formInfo } = record;
      this.id = id;
      this.defaultObj = { formInfo };
      this.adjustShow = true;
    },
    handlePull(id, userid) {
      this.id = id;
      this.userid = userid
      this.formShow = true;
    },
    handlePull1(id, userid) {
      this.id = id;
      this.userid = userid
      // console.log(userid)
      this.formShow1 = true;
    },
    successForm() {

      this.tableInit();
      this.closeForm();
      // this.$router.go(0)
    },
    successForm1() {
      this.tableInit();
      this.closeForm1();
    },
    closeForm() {
      this.formShow = false;
      this.id = '';
    },
    closeForm1() {
      this.formShow1 = false;
      this.id = '';
    },
    closeAdjust() {
      this.adjustShow = false;
      this.id = '';
      this.defaultObj = {};
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.ant-tag) {
  margin-bottom: 4px;
}

.popover-content {
  max-width: 600px;
}

.row {
  display: flex;

  &:not(:last-child) {
    margin-bottom: 4px;
  }

  &:last-child {
    margin-top: 8px;
  }

  .label {
    margin-right: 8px;
    min-width: 60px;
    text-align: right;
  }

  .value {
    min-width: 80px;
    color: #999;
  }
}

.table-wrap {
  margin-top: 16px;
}

.table-top-wrap {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.table-img {
  max-height: 20px;
  max-width: 100px;
}

.table-title {
  flex: 1;

  span {
    line-height: 32px;
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;

    &::before {
      content: '';
      display: block;
      width: 3px;
      height: 18px;
      background-color: #1890ff;
      margin-right: 8px;
      position: relative;
      top: -1px;
    }
  }
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;

  &>button {
    margin-left: 12px;

    &:first-child {
      margin-left: 0;
    }
  }
}

// ::v-deep .ant-table-tbody{
//   background-color: red !important;
// }</style>
